#!/usr/bin/python3
# coding: utf-8
# file: models.py
# 2018-06-21
from .ext import db
from datetime import datetime
from markdown import markdown
from markdown.extensions.codehilite import CodeHiliteExtension
from markdown.extensions.extra import ExtraExtension

from micawber import bootstrap_basic, parse_html
from micawber.cache import Cache as OEmbedCache
from flask import Markup
oembed_providers = bootstrap_basic(OEmbedCache())


class Post(db.Model):
	__tablename__='posts'
	id=db.Column(db.Integer,primary_key=True)
	title=db.Column(db.String(80))
	content=db.Column(db.Text)
	timestamp=db.Column(db.DateTime,index=True,default=datetime.utcnow)
	published=db.Column(db.Boolean,index=True,default=False)
	category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
	category = db.relationship('Category',backref=db.backref('posts', lazy='dynamic'))

	def __init__(self,title,content,category,published=False):
		self.title=title
		self.content=content
		self.category=category
		if published:
			self.published=True

	@property
	def html_content(self):
		hilite = CodeHiliteExtension(linenums=False, css_class='highlight')
		extras = ExtraExtension()
		markdown_content = markdown(self.content, extensions=[hilite, extras])
		oembed_content = parse_html(
			markdown_content,
			oembed_providers,
			urlize_all=True,
			maxwidth=app.config['SITE_WIDTH'])
		return Markup(oembed_content)
	
	def __repr__(self):
		return '<Post %r>' % self.title

class Category(db.Model):
	id=db.Column(db.Integer, primary_key=True)
	name=db.Column(db.String(50),unique=True)
	
	def __repr__(self):
		return '<Category %r>' % self.name
